package com.example.managemyself.api.controller;

import com.example.managemyself.api.entity.HealthData;
import com.example.managemyself.api.repository.HealthDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.sql.Connection;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 健康数据控制器
 * 处理健康数据相关的HTTP请求
 */
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class HealthController {
    
    @Autowired
    private HealthDataRepository healthDataRepository;
    
    @Autowired
    private DataSource dataSource;
    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查数据库连接
            boolean dbHealthy = checkDatabaseHealth();
            
            response.put("status", dbHealthy ? "UP" : "DOWN");
            response.put("timestamp", LocalDateTime.now());
            response.put("application", "ManageMyself API");
            response.put("version", "1.0.0");
            response.put("database", dbHealthy ? "Connected" : "Disconnected");
            
            if (dbHealthy) {
                response.put("message", "API服务运行正常");
                return ResponseEntity.ok(response);
            } else {
                response.put("message", "数据库连接异常");
                return ResponseEntity.status(503).body(response);
            }
            
        } catch (Exception e) {
            response.put("status", "DOWN");
            response.put("timestamp", LocalDateTime.now());
            response.put("error", e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 简单的健康检查接口 - 不需要数据库连接
     */
    @GetMapping("/health/check")
    public ResponseEntity<Map<String, Object>> simpleHealthCheck() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("timestamp", LocalDateTime.now());
        response.put("application", "ManageMyself API");
        response.put("version", "1.0.0");
        response.put("message", "API服务运行正常");
        return ResponseEntity.ok(response);
    }
    
    /**
     * API信息接口
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> info() {
        Map<String, Object> response = new HashMap<>();
        
        response.put("application", "ManageMyself API");
        response.put("version", "1.0.0");
        response.put("description", "个人管理系统后端API服务");
        response.put("database", "MySQL");
        response.put("framework", "Spring Boot 2.7.0");
        response.put("java", System.getProperty("java.version"));
        response.put("timestamp", LocalDateTime.now());
        
        // API端点信息
        Map<String, String> endpoints = new HashMap<>();
        endpoints.put("用户管理", "/api/users");
        endpoints.put("任务管理", "/api/tasks");
        endpoints.put("健康检查", "/api/health");
        endpoints.put("API信息", "/api/info");
        
        response.put("endpoints", endpoints);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 数据库状态检查
     */
    @GetMapping("/db-status")
    public ResponseEntity<Map<String, Object>> databaseStatus() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean dbHealthy = checkDatabaseHealth();
            
            response.put("database", "MySQL");
            response.put("status", dbHealthy ? "Connected" : "Disconnected");
            response.put("timestamp", LocalDateTime.now());
            
            if (dbHealthy) {
                try (Connection connection = dataSource.getConnection()) {
                    response.put("url", connection.getMetaData().getURL());
                    response.put("driver", connection.getMetaData().getDriverName());
                    response.put("version", connection.getMetaData().getDatabaseProductVersion());
                }
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("status", "Error");
            response.put("error", e.getMessage());
            response.put("timestamp", LocalDateTime.now());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 检查数据库健康状态
     */
    private boolean checkDatabaseHealth() {
        try (Connection connection = dataSource.getConnection()) {
            return connection.isValid(5); // 5秒超时
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 获取用户的所有健康数据
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserHealthData(@PathVariable Integer userId) {
        try {
            List<HealthData> healthDataList = healthDataRepository.findByUserIdOrderByRecordDateDesc(userId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", healthDataList);
            response.put("message", "获取健康数据成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取健康数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 获取用户指定日期的健康数据
     */
    @GetMapping("/user/{userId}/date/{date}")
    public ResponseEntity<Map<String, Object>> getHealthDataByDate(@PathVariable Integer userId, @PathVariable String date) {
        try {
            LocalDate recordDate = LocalDate.parse(date);
            Optional<HealthData> healthDataOptional = healthDataRepository.findByUserIdAndRecordDate(userId, recordDate);
            
            Map<String, Object> response = new HashMap<>();
            if (healthDataOptional.isPresent()) {
                response.put("success", true);
                response.put("data", healthDataOptional.get());
                response.put("message", "获取健康数据成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "该日期没有健康数据记录");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取健康数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 获取用户最近N天的健康数据
     */
    @GetMapping("/user/{userId}/recent")
    public ResponseEntity<Map<String, Object>> getRecentHealthData(@PathVariable Integer userId, 
                                                                  @RequestParam(defaultValue = "7") int days) {
        try {
            LocalDate startDate = LocalDate.now().minusDays(days - 1);
            List<HealthData> healthDataList = healthDataRepository.findRecentHealthData(userId, startDate);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", healthDataList);
            response.put("message", "获取最近" + days + "天健康数据成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取最近健康数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 获取用户最新的健康数据
     */
    @GetMapping("/user/{userId}/latest")
    public ResponseEntity<Map<String, Object>> getLatestHealthData(@PathVariable Integer userId) {
        try {
            Optional<HealthData> healthDataOptional = healthDataRepository.findTopByUserIdOrderByRecordDateDesc(userId);
            
            Map<String, Object> response = new HashMap<>();
            if (healthDataOptional.isPresent()) {
                response.put("success", true);
                response.put("data", healthDataOptional.get());
                response.put("message", "获取最新健康数据成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "没有健康数据记录");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取最新健康数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 根据ID获取健康数据
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getHealthDataById(@PathVariable Integer id) {
        try {
            Optional<HealthData> healthDataOptional = healthDataRepository.findById(id);
            Map<String, Object> response = new HashMap<>();
            
            if (healthDataOptional.isPresent()) {
                response.put("success", true);
                response.put("data", healthDataOptional.get());
                response.put("message", "获取健康数据详情成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "健康数据不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取健康数据详情失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 创建或更新健康数据
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createOrUpdateHealthData(@RequestBody HealthData healthData) {
        try {
            // 检查是否已存在该日期的记录
            Optional<HealthData> existingData = healthDataRepository.findByUserIdAndRecordDate(
                healthData.getUserId(), healthData.getRecordDate());
            
            HealthData savedHealthData;
            String message;
            
            if (existingData.isPresent()) {
                // 更新现有记录
                HealthData existing = existingData.get();
                if (healthData.getWeight() != null) existing.setWeight(healthData.getWeight());
                if (healthData.getHeight() != null) existing.setHeight(healthData.getHeight());
                if (healthData.getSleepHours() != null) existing.setSleepHours(healthData.getSleepHours());
                if (healthData.getMoodScore() != null) existing.setMoodScore(healthData.getMoodScore());
                if (healthData.getEnergyLevel() != null) existing.setEnergyLevel(healthData.getEnergyLevel());
                if (healthData.getStepsCount() != null) existing.setStepsCount(healthData.getStepsCount());
                if (healthData.getNotes() != null) existing.setNotes(healthData.getNotes());
                
                savedHealthData = healthDataRepository.save(existing);
                message = "健康数据更新成功";
            } else {
                // 创建新记录
                savedHealthData = healthDataRepository.save(healthData);
                message = "健康数据创建成功";
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", savedHealthData);
            response.put("message", message);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "保存健康数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 更新健康数据
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateHealthData(@PathVariable Integer id, @RequestBody HealthData healthDataDetails) {
        try {
            Optional<HealthData> healthDataOptional = healthDataRepository.findById(id);
            Map<String, Object> response = new HashMap<>();
            
            if (healthDataOptional.isPresent()) {
                HealthData healthData = healthDataOptional.get();
                
                // 更新健康数据
                if (healthDataDetails.getWeight() != null) {
                    healthData.setWeight(healthDataDetails.getWeight());
                }
                if (healthDataDetails.getHeight() != null) {
                    healthData.setHeight(healthDataDetails.getHeight());
                }
                if (healthDataDetails.getSleepHours() != null) {
                    healthData.setSleepHours(healthDataDetails.getSleepHours());
                }
                if (healthDataDetails.getMoodScore() != null) {
                    healthData.setMoodScore(healthDataDetails.getMoodScore());
                }
                if (healthDataDetails.getEnergyLevel() != null) {
                    healthData.setEnergyLevel(healthDataDetails.getEnergyLevel());
                }
                if (healthDataDetails.getStepsCount() != null) {
                    healthData.setStepsCount(healthDataDetails.getStepsCount());
                }
                if (healthDataDetails.getNotes() != null) {
                    healthData.setNotes(healthDataDetails.getNotes());
                }
                
                HealthData updatedHealthData = healthDataRepository.save(healthData);
                
                response.put("success", true);
                response.put("data", updatedHealthData);
                response.put("message", "健康数据更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "健康数据不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新健康数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 删除健康数据
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteHealthData(@PathVariable Integer id) {
        try {
            Map<String, Object> response = new HashMap<>();
            
            if (healthDataRepository.existsById(id)) {
                healthDataRepository.deleteById(id);
                response.put("success", true);
                response.put("message", "健康数据删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "健康数据不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除健康数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
} 